﻿using System;
using System.Drawing;
using System.IO;
using System.Web.UI.WebControls;
using BONSAI.BLL;
using BONSAI.Common;
using BONSAI.Common.DTO;
using BONSAI.Common.Enum;

namespace BONSAI.Admin.UC
{
    public partial class ProductsUpdate : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDropLoadLoaiTours();
                BindLoad();
                
            }
        }

        public void BindDropLoadLoaiTours()
        {
            var list = new ListItem("Tất cả", "0");
            var table = (new TypeProductsBO()).GetAll();

            foreach (var dto in table)
            {
                dropLoaiTours.Items.Add(new ListItem(dto.NameFull, dto.TypeProductsID));
            }

            dropLoaiTours.Items.Insert(0, list);
        }

        public void BindLoad()
        {
            if (Request.QueryString["id"] != null)
            {
                var table = (new ProductsBo()).GetById(Request.QueryString["id"]);
                if (table != null)
                {
                    dropLoaiTours.SelectedValue = table.TypeProductsID;
                    txttensNgan.Text = table.NameFull;
                    txtGiaOld.Text = table.PriceOld.ToString();
                    txtGiaNew.Text = table.Pricenew.ToString();
                    txtspcodes.Text = table.ProductsCode;
                    fckchitietTV.Value = table.Description;
                    chkchoosenew.Checked = table.Isnew;
                    Session[BONSAIConstants.OLD_THUMBNAIL] = table.thumbnail;
                    Session[BONSAIConstants.OLD_PREVIEW] = table.preview;

                    if (table.thumbnail != null)
                    {
                        Image1.ImageUrl = table.thumbnail;
                        Session["imgThubnail"] = table.thumbnail;
                    }

                    Application[BONSAIConstants.LISTPRODUCTSNEW] = (new ProductsBo()).GetNew(true);
                }
            }
        }

        protected void btcapnhat_Click(object sender, EventArgs e)
        {
            #region check value

            if (dropLoaiTours.SelectedValue == "0")
            {
                WebMBox.Show("Vui lòng chọn loại tours.");
                return;
            }

            // gia tours
            if (txtGiaOld.Text == "")
            {
                WebMBox.Show("Vui lòng nhập giá tours Tiếng Việt.");
                return;
            }

            #endregion
            //===================

            //=====================
            if (Request.QueryString["id"] != null) // edit
            {
                var productDto = new ProductsDTO();

                productDto.ProductsID = Request.QueryString["id"];
                                  productDto.NameFull = txttensNgan.Text;
                productDto.ProductsCode = txtspcodes.Text;
                if (!string.IsNullOrEmpty(txtGiaOld.Text))
                {
                    productDto.PriceOld = Double.Parse(txtGiaOld.Text);

                }
                if (!string.IsNullOrEmpty(txtGiaNew.Text))
                {
                    productDto.Pricenew = Double.Parse(txtGiaNew.Text);

                }
                productDto.Isnew = chkchoosenew.Checked;
                productDto.Description = fckchitietTV.Value;
                productDto.TypeProductsID = dropLoaiTours.SelectedValue;
                productDto.Createdate = DateTime.Now;
                const bool error = false;
                UploadImageForUpdate(productDto, error, BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS);

                (new ProductsBo()).UpdateByID(productDto);
                Response.Redirect("ProductManager.aspx");
            }
            else // create new
            {
                var productDto = new ProductsDTO();

                productDto.NameFull = txttensNgan.Text;
                productDto.ProductsCode = txtspcodes.Text;
                if (!string.IsNullOrEmpty(txtGiaOld.Text))
                {
                    productDto.PriceOld = Double.Parse(txtGiaOld.Text);

                }
                if (!string.IsNullOrEmpty(txtGiaNew.Text))
                {
                    productDto.Pricenew = Double.Parse(txtGiaNew.Text);

                }
                productDto.Isnew = chkchoosenew.Checked;
                productDto.Description = fckchitietTV.Value;
                productDto.TypeProductsID = dropLoaiTours.SelectedValue;
                productDto.Createdate = DateTime.Now;
                                     
                const bool error = false;
                UploadImageForAdd(productDto, error, BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS);
                (new ProductsBo()).Insert(productDto);
                Response.Redirect("ProductManager.aspx");
            }
        }
        #region UploadImageForAdd
        /// <summary>
        /// Method : UploadImageForAdd
        /// Author : LinhVM
        /// Creation date : 22.Jul.2009
        /// </summary>
        /// <param name="newsDTO"></param>
        /// <param name="error"></param>
        /// <param name="relativePhotos"></param>
        /// <returns></returns>
        private bool UploadImageForAdd(ProductsDTO info, bool error, string relativePhotos)
        {
            // First we check to see if the user has selected a file
            if (!FileUpload1.HasFile)
            {
                return error;
            }
            // Check if the directory we want the image uploaded to actually exists or not
            if (!Directory.Exists(MapPath(relativePhotos)))
            {
                // If it doesn't then we just create it before going any further
                Directory.CreateDirectory(MapPath(relativePhotos));
            }

            // get server path to save image
            string pathServer = Server.MapPath(relativePhotos);

            // upload image to server
            //try
            //{
                // resize before save image
                // Create a bitmap of the content of the fileUpload control in memory
                Bitmap originalBMP = null;
                originalBMP = new Bitmap(FileUpload1.FileContent);
                string relativeImageUrl = string.Empty;
                string relativePreviewUrl = string.Empty;
                // make thumbnail and preview for image
                int result = 0;
                result = BONSAIUtils.ImageUtil.DoImageTasks(originalBMP, pathServer, relativePhotos,
                                                                      ref relativeImageUrl, ref relativePreviewUrl,
                                                                      UploadImageEnum.PRODUCT_IMAGE, "");

                if (result == 1)
                {
                    info.thumbnail = relativeImageUrl;
                    info.preview = relativePreviewUrl;
                    error = false;
                }
                else
                {
                    error = true;
                }
            //}
            //catch (Exception)
            //{
            //    error = true;
            //}

            return error;
        }

        #endregion UploadImageForAdd

        #region UploadImageForUpdate
        /// <summary>
        /// Method : UploadImageForUpdate
        /// Author : LinhVM
        /// Creation date : 22.Jul.2009
        /// </summary>
        /// <param name="info"></param>
        /// <param name="error"></param>
        /// <param name="relativePhotos"></param>
        /// <returns></returns>
        private bool UploadImageForUpdate(ProductsDTO info, bool error, string relativePhotos)
        {
            // First we check to see if the user has selected a file

            if (!FileUpload1.HasFile)
            {
                if (Session[BONSAIConstants.OLD_THUMBNAIL] == null)
                {

                    error = true;
                    return error;
                }

                info.thumbnail = Session[BONSAIConstants.OLD_THUMBNAIL].ToString();
                info.preview = Session[BONSAIConstants.OLD_PREVIEW].ToString();

                error = false;
                return error;
            }

            // Check if the directory we want the image uploaded to actually exists or not
            if (!Directory.Exists(MapPath(relativePhotos)))
            {
                // If it doesn't then we just create it before going any further
                Directory.CreateDirectory(MapPath(relativePhotos));
            }

            // get server path to save image
            string pathServer = Server.MapPath(relativePhotos);

            // upload image to server
            //try
            //{
                // resize before save image

                // Create a bitmap of the content of the fileUpload control in memory
                Bitmap originalBMP = null;

                originalBMP = new Bitmap(FileUpload1.FileContent);

                string relativeImageUrl = string.Empty;
                string relativePreviewUrl = string.Empty;

                // make thumbnail and preview for image
                int result = 0;

                result = BONSAIUtils.ImageUtil.DoImageTasks(originalBMP, pathServer, relativePhotos,
                                                                      ref relativeImageUrl, ref relativePreviewUrl,
                                                                      UploadImageEnum.PRODUCT_IMAGE, "");

                if (result == 1)
                {
                    // upload image successful
                    // set relative url
                    if (Session[BONSAIConstants.OLD_THUMBNAIL] != null)
                    {
                        BONSAIUtils.ImageUtil.ClearOldImageOnServer(
                                       Server.MapPath(BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS),
                                       Session[BONSAIConstants.OLD_THUMBNAIL].ToString());
                    }
                    if (Session[BONSAIConstants.OLD_PREVIEW] != null)
                    {
                        BONSAIUtils.ImageUtil.ClearOldImageOnServer(
                            Server.MapPath(BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS),
                            Session[BONSAIConstants.OLD_PREVIEW].ToString());
                    }


                    info.thumbnail = relativeImageUrl;
                    info.preview = relativePreviewUrl;
                    error = false;
                }
                else
                {
                    error = true;
                }

            //}
            //catch (Exception)
            //{
            //    error = true;
            //}

            return error;
        }

        #endregion UploadImageForUpdate
    }
}